package com.northwind.serviceImpl;


import com.northwind.entity.Admin;
import com.northwind.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.util.HashMap;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {
    @Resource
    HttpSession session;


   // @LoginCache
    @Override
    public HashMap<String, Object> loginShiro (Admin admin, String enCode) {
        //先判断验证码,用户是否存在，密码是否正确
        String imageCode = (String) session.getAttribute("imageCode");
        HashMap<String, Object> map = new HashMap<>();

        System.out.println("session验证码:"+imageCode);
       // System.out.println("输入验证码:"+enCode);
        if(imageCode == null){
            //验证码正确
            //Admin admin1 = adminDao.queryByUsername(admin.getUsername());
            //获取主体对象
            Subject subject = SecurityUtils.getSubject();
            //创建token
            UsernamePasswordToken token = new UsernamePasswordToken(admin.getUsername(), admin.getPassword());
            try {
                //认证
                subject.login(token);

                System.out.println("100,登陆成功");
                map.put("status","100");
                map.put("message","登录成功");
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                map.put("status","101");
                map.put("message","用户名不存在");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                map.put("status","101");
                map.put("message","密码错误");
            }
        }else{
            map.put("status","101");
            map.put("message","验证码错误");
        }
        return map;
    }
}
